package com.qiaoba.file.aliyun.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.qiaoba.api.file.core.FileCore;
import com.qiaoba.api.file.entity.vo.FileUploadVO;
import com.qiaoba.api.file.util.FileUtil;
import com.qiaoba.file.aliyun.config.AliyunConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云 文件服务实现
 *
 * @author ailanyin
 * @date 2023-09-26 14:36:52
 */
@Service
@RequiredArgsConstructor
public class AliyunFileServiceImpl implements FileCore {

    private final OSS ossClient;

    @Override
    public FileUploadVO upload(String bucketName, String filename, Long size, InputStream inputStream) {
        try {
            createBucket(bucketName);
            // 设置存储对象名称
            String objectName = DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + UUID.randomUUID().toString() + "." + FileUtil.getExtension(filename);
            // 上传文件
            ossClient.putObject(bucketName, objectName, inputStream);

            FileUploadVO vo = new FileUploadVO();
            vo.setUrl(createUrl(bucketName, objectName));
            vo.setFileName(filename);
            vo.setPath(objectName);
            return vo;
        } finally {
            IoUtil.close(inputStream);
        }
    }

    @Override
    public void delete(String bucketName, String path) {
        ossClient.deleteObject(bucketName, path);
    }

    private void createBucket(String bucketName) {
        // 检查存储桶是否存在
        boolean exist = ossClient.doesBucketExist(bucketName);
        if (!exist) {
            // 新建存储桶
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            //设置权限为公开读
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }
    }

    private String createUrl(String bucketName, String objectName) {
        // https://tlias-backend.oss-cn-beijing.aliyuncs.com/test.png
        String[] split = AliyunConfig.endpoint.split("//");
        return split[0] + "//" + bucketName + "." + split[1] + "/" + objectName;
    }
}
